package com.boarsoft.demo.order;

import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.boarsoft.boar.demo.order.entity.PocOrder;
import com.boarsoft.boar.demo.order.service.PocOrderService;
import com.boarsoft.rpc.core.RpcCore;

public class OrderFindClient extends AbstractJavaSamplerClient {
	private static final Logger log = LoggerFactory.getLogger(OrderFindClient.class);

	public static volatile ClassPathXmlApplicationContext ctx;
	public static volatile PocOrderService orderService;

	@Override
	public SampleResult runTest(JavaSamplerContext jsc) {
		SampleResult sr = new SampleResult();
//		try {
			sr.sampleStart();
			int tenantId = 12344;
			int orderId = 1;
			if (jsc != null) {
				tenantId = jsc.getIntParameter("tenantId", tenantId);
				orderId = jsc.getIntParameter("orderId", orderId);
			}
			PocOrder o = orderService.find(tenantId, orderId);
			String s = o.toString();
			// System.out.println(s);
			sr.setResponseData(s, "UTF-8");
			sr.setDataType(SampleResult.TEXT);
			sr.setSuccessful(true);
			sr.sampleEnd();
//		} catch (Exception e) {
//			log.error("Error on run test", e);
//		}
		return sr;
	}

	@Override
	public void setupTest(JavaSamplerContext jsc) {
		synchronized (OrderFindClient.class) {
			if (ctx == null) {
				ctx = new ClassPathXmlApplicationContext("classpath:conf/context.xml");
				orderService = ctx.getBean(PocOrderService.class);
			}
		}
	}

	@Override
	public void teardownTest(JavaSamplerContext context) {
		log.info("RpcCore is shutting down");
		try {
			RpcCore.getCurrentInstance().shutdown();
		} catch (Exception e) {
			log.error("Error on close application context", e);
		} finally {
			ctx.close();
		}
	}

	public static void main(String[] args) {
		OrderFindClient osc = new OrderFindClient();
		osc.setupTest(null);
		osc.runTest(null);
	}
}
